/*
 * EntityMaker.java
 */
package mango.orm.entity.maker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import mango.Mango;
import mango.functions.FuncString;

/**
 * 用PDM文件生成实体类
 * 
 * @author zhangms
 */
public final class Maker {
    /**
     * 执行生成
     * 
     * @param pkg
     *            生成类所在的包名
     * @param output
     *            生成文件根目录
     * @param pdmfile
     *            pdm文件位置
     * @throws Exception
     */
    public static void executePDM(String pkg, String output, String pdmfile, String tableName)
            throws Exception {
        List<EOTable> tables = null;
        if (FuncString.isBlank(tableName)) {
            tables = PDMParser.parse(pdmfile);
        }
        else {
            tables = new ArrayList<EOTable>();
            String[] tableNames = tableName.split(",");
            for (String tname : tableNames) {
                tables.addAll(PDMParser.parse(pdmfile, tname));
            }
        }
        Iterator<EOTable> iter = tables.iterator();
        while (iter.hasNext()) {
            EOTable t = iter.next();
            t.setPkg(pkg);
            String entityStr = EOTableParser.parse(t);
            String fileName = t.getJavaClassName() + ".java";
            Mango.getLog().debug(fileName + " : 开始");
            Mango.getLog().debug(entityStr);
            Maker.output(output, pkg, fileName, entityStr);
            Mango.getLog().debug(fileName + " : 结束");
        }
    }

    public static void executeOracleTable(String pkg, String output, String tableNames)
            throws Exception {
        String[] tables = tableNames.split(",");
        for (String tableName : tables) {
            EOTable t = OracleTableParser.parse(tableName);
            t.setPkg(pkg);
            String entityStr = EOTableParser.parse(t);
            String fileName = t.getJavaClassName() + ".java";
            Mango.getLog().debug(fileName + " : 开始");
            Mango.getLog().debug(entityStr);
            Maker.output(output, pkg, fileName, entityStr);
            Mango.getLog().debug(fileName + " : 结束");
        }
    }

    private static void output(String output, String pkg, String fileName, String entityStr)
            throws IOException {
        String pkgPath = pkg.replace(".", File.separator);
        String filePath = output + File.separator + pkgPath + File.separator;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(filePath + fileName);
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write(entityStr);
        writer.flush();
        writer.close();
    }
}
